package com.ysyc.driver_ee.api;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.RequestBody;
import retrofit2.Converter;

public final class GsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
    private Gson gson;

    GsonRequestBodyConverter(Gson gson) {
        this.gson = gson;
    }

    @Override
    public RequestBody convert(T value) throws IOException {
        String jsonStr = gson.toJson(value);

        Map<String,String> map = new Gson().fromJson(jsonStr, new TypeToken<HashMap<String,String>>(){}.getType());

        FormBody.Builder builder = new FormBody.Builder();

        for(String key : map.keySet()) {
            builder.add(key,map.get(key));
        }
        return builder.build();
    }
}
